import { onMounted, reactive, ref } from "vue"

export interface SelectOption {
  value: string
  label: string
  disabled?: boolean
  key: string
}

interface FetchSelectProps {
  apiFunc: () => Promise<any>
}
export function useRequestSelect(props: FetchSelectProps) {
  const { apiFunc } = props
  const options = ref<SelectOption[]>([])
  const loading = ref(false)

  const loadData = () => {
    loading.value = false
    options.value = []
    return apiFunc().then(
      (data) => {
        if (data.code === 0) {
          options.value = data
          return data
        }
        loading.value = false
        return []
      },
      (err) => {
        loading.value = false
        options.value = []
        return Promise.reject(err)
      }
    )
  }
  onMounted(() => {
    loadData()
  })
  return reactive({
    options,
    loading
  })
}
